<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\RunGameReward as Reward;
use DB;

class RunGameReward extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rungame:reward';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '将预设得游戏奖品上架并下架无效的奖品';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 检测脚本是否重复执行
        $this->check();
        $time = time();

        DB::beginTransaction();

        //找出三个等级上架时间离现在最近的奖品各一个
        $first = Reward::where('start_at', '<=', $time)->where('ranking', 1)->orderByDesc('start_at')->value('id');
        $second = Reward::where('start_at', '<=', $time)->where('ranking', 2)->orderByDesc('start_at')->value('id');
        $third = Reward::where('start_at', '<=', $time)->where('ranking', 3)->orderByDesc('start_at')->value('id');

        //把所有的状态都改成下架
        DB::table('run_game_reward')->where('id', '!=', 0)->update(['is_use' => Reward::USE_NO]);
//        if (!) {
//            DB::rollBack();
//
//            logger('所有的状态都改成下架失败');
//            exit('所有的状态都改成下架失败');
//        }

        //将应该上架的奖品状态改为上架
        if (!Reward::whereIn('id',[$first, $second, $third])->update(['is_use' => Reward::USE_YES])) {
            DB::rollBack();

            logger('上架失败');
            exit('上架失败');
        }
        DB::commit();

        exit('ok');
    }

    public function check()
    {
        $file = 'rungame_reward.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
